<template>
  <div class="doctor-schedule-container">
    <div class="header">
      <h1>我的排班表</h1>
      <p class="subtitle">本周工作安排</p>
    </div>
    
    <div class="doctor-card">
      <div class="avatar-container">
        <img :src="doctorInfo.img" alt="医生头像" class="doctor-avatar">
        <div class="status-indicator" :class="{ online: true }"></div>
      </div>
      <div class="doctor-meta">
        <h2>{{ doctorInfo.doc_name }} <span class="title-badge">{{ doctorInfo.doc_title }}</span></h2>
        <p class="department">{{ getDepartmentName(doctorInfo.depart_id1) }} - {{ getDepartmentName(doctorInfo.depart_id2) }}</p>
        <div class="contact-info">
          <span class="contact-item">
            <i class="icon-phone"></i> {{ doctorInfo.telephone }}
          </span>
        </div>
      </div>
      <div class="doctor-bio">
        <p>{{ doctorInfo.introduction || "暂无个人简介" }}</p>
      </div>
    </div>
    
    <div class="schedule-container">
      <div class="week-navigation">
        <button class="nav-button" @click="changeWeek(-1)">
          <i class="icon-arrow-left"></i> 上周
        </button>
        <span class="current-week">{{ currentWeekRange }}</span>
        <button class="nav-button" @click="changeWeek(1)">
          下周 <i class="icon-arrow-right"></i>
        </button>
      </div>
      
      <div class="schedule-grid">
        <div class="grid-header">
          <div class="grid-time-label"></div>
          <div class="grid-day" v-for="day in weekDays" :key="day.date">
            <div class="weekday">{{ day.weekday }}</div>
            <div class="date" :class="{ today: isToday(day.date) }">{{ day.date.split('月')[1] }}</div>
          </div>
        </div>
        
        <div class="grid-row">
          <div class="grid-time-label">上午 <span class="time-range">8:00-12:00</span></div>
          <div class="grid-cell" v-for="day in weekDays" :key="day.date + 'am'">
            <div :class="['shift-indicator', { working: day.amwork }]">
              <template v-if="day.amwork">
                <span class="shift-text">{{ day.amwork }}</span>
                <i class="icon-location"></i>
              </template>
              <span v-else class="shift-text">休息</span>
            </div>
          </div>
        </div>
        
        <div class="grid-row">
          <div class="grid-time-label">下午 <span class="time-range">14:00-18:00</span></div>
          <div class="grid-cell" v-for="day in weekDays" :key="day.date + 'pm'">
            <div :class="['shift-indicator', { working: day.pmwork }]">
              <template v-if="day.pmwork">
                <span class="shift-text">{{ day.pmwork }}</span>
                <i class="icon-location"></i>
              </template>
              <span v-else class="shift-text">休息</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="stats-card">
      <div class="stat-item">
        <div class="stat-value">{{ workingDays }}</div>
        <div class="stat-label">工作日</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ differentRooms }}</div>
        <div class="stat-label">不同诊室</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ nextWorkingDay || '无' }}</div>
        <div class="stat-label">下次值班</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import axios from 'axios'

const userStore = useUserStore()
const doctorInfo = ref({})
const scheduleData = ref([])
const loading = ref(true)
const currentWeekOffset = ref(0) // 用于周切换

// 模拟科室数据
const departments = {
  1: "内科",
2: "外科",
3: "妇科",
4: "儿科",
5: "传染病",
6: "五官科",
7: "中医科",
8: "检验科",
9: "放射科",
10: "超声科",
11: "胃镜科",
12: "药剂科",
13: "行政科室",
14: "神经内科",
15: "急诊科",
16: "康复科",
17: "心理科",
18: "营养科",
19: "病理科",
20: "心外科",
28: "妇产科",
38: "发烧发热",
39: "皮肤外科",
51: "传染预防科",
52: "心内科",
53: "骨外科",
54: "CT 门诊",
61: "耳鼻喉",
100: "呼吸内科",
101: "消化内科",
102: "神经外科",
103: "妇科肿瘤",
104: "生殖医学科",
105: "新生儿科",
106: "儿童保健科",
107: "感染性疾病科",
108: "结核病科",
109: "眼科",
110: "口腔科",
111: "针灸科",
112: "推拿科",
113: "中医康复科",
114: "生化检验",
115: "免疫检验",
116: "微生物检验",
117: "MRI 室",
118: "X 光室",
119: "心脏超声",
120: "腹部超声",
121: "妇产超声",
122: "普通胃镜",
123: "无痛胃镜",
124: "肠镜检查",
125: "门诊药房",
126: "住院药房",
127: "临床药学",
128: "人事科",
129: "财务科",
130: "医务科",
131: "急诊内科",
132: "急诊外科",
133: "急诊儿科",
134: "物理治疗科",
135: "作业治疗科",
136: "言语治疗科",
137: "心理咨询",
138: "心理治疗",
139: "儿童心理科",
140: "临床营养",
141: "膳食管理",
142: "营养评估",
143: "组织病理",
144: "细胞病理",
145: "分子病理"
}

const getDepartmentName = (id) => {
  return departments[id] || `科室${id}`
}

// 获取当前周的周一到周五日期
const getCurrentWeekDays = (offset = 0) => {
  const now = new Date()
  now.setDate(now.getDate() + offset * 7)
  const currentDay = now.getDay()
  const monday = new Date(now)
  
  if (currentDay === 0) {
    monday.setDate(monday.getDate() + 1)
  } else {
    monday.setDate(monday.getDate() - (currentDay - 1))
  }
  
  const weekDays = []
  const weekdays = ['周一', '周二', '周三', '周四', '周五']
  
  for (let i = 0; i < 5; i++) {
    const day = new Date(monday)
    day.setDate(monday.getDate() + i)
    
    const formattedDate = `${day.getMonth() + 1}月${day.getDate()}日`
    const dateString = `${day.getFullYear()}-${(day.getMonth() + 1).toString().padStart(2, '0')}-${day.getDate().toString().padStart(2, '0')}`
    
    weekDays.push({
      date: formattedDate,
      weekday: weekdays[i],
      dayString: dateString,
      dateObj: new Date(day),
      amwork: null,
      pmwork: null
    })
  }
  
  return weekDays
}

const weekDays = ref(getCurrentWeekDays())

// 计算当前周的范围显示文本
const currentWeekRange = computed(() => {
  if (weekDays.value.length === 0) return ''
  const firstDay = weekDays.value[0].dateObj
  const lastDay = weekDays.value[4].dateObj
  return `${firstDay.getMonth() + 1}月${firstDay.getDate()}日 - ${lastDay.getMonth() + 1}月${lastDay.getDate()}日`
})

// 切换周
const changeWeek = (offset) => {
  currentWeekOffset.value += offset
  weekDays.value = getCurrentWeekDays(currentWeekOffset.value)
  updateWeekSchedule(scheduleData.value)
}

// 检查是否是今天
const isToday = (dateStr) => {
  const today = new Date()
  const dateParts = dateStr.split('月')
  const month = parseInt(dateParts[0])
  const day = parseInt(dateParts[1].replace('日', ''))
  return today.getMonth() + 1 === month && today.getDate() === day
}

// 统计信息
const workingDays = computed(() => {
  return weekDays.value.filter(day => day.amwork || day.pmwork).length
})

// 统计不同诊室数量
const differentRooms = computed(() => {
  const rooms = new Set()
  weekDays.value.forEach(day => {
    if (day.amwork) rooms.add(day.amwork)
    if (day.pmwork) rooms.add(day.pmwork)
  })
  return rooms.size
})

const nextWorkingDay = computed(() => {
  const today = new Date()
  const nextDay = weekDays.value.find(day => {
    return (day.amwork || day.pmwork) && 
           (day.dateObj > today || isToday(day.date))
  })
  
  if (!nextDay) return null
  
  let shift = []
  if (nextDay.amwork) shift.push(`上午: ${nextDay.amwork}`)
  if (nextDay.pmwork) shift.push(`下午: ${nextDay.pmwork}`)
  
  return `${nextDay.weekday} ${shift.join(' / ')}`
})

// 获取医生信息
const fetchDoctorInfo = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/hospital5/doctor/findByUserName?user_name=${userStore.userInfo.userName}`)
    doctorInfo.value = response.data[0]
    return response.data[0].doc_id
  } catch (error) {
    console.error('获取医生信息失败:', error)
    return null
  }
}

// 获取医生排班信息
const fetchScheduleData = async (docId) => {
  try {
    const response = await axios.get(`http://localhost:8080/hospital5/doctorWork/findByDocId?docId=${docId}`)
    scheduleData.value = response.data
    updateWeekSchedule(response.data)
  } catch (error) {
    console.error('获取排班信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 更新本周排班数据
const updateWeekSchedule = (allSchedules) => {
  weekDays.value = weekDays.value.map(day => {
    const schedule = allSchedules.find(s => s.day === day.dayString)
    return {
      ...day,
      amwork: schedule ? schedule.amwork : null,
      pmwork: schedule ? schedule.pmwork : null
    }
  })
}

onMounted(async () => {
  const docId = await fetchDoctorInfo()
  if (docId) {
    await fetchScheduleData(docId)
  }
})
</script>

<style scoped>
.doctor-schedule-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #333;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  font-size: 2.2rem;
  color: #2c3e50;
  margin-bottom: 5px;
}

.subtitle {
  font-size: 1rem;
  color: #7f8c8d;
}

/* 医生卡片样式 */
.doctor-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  display: flex;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  position: relative;
  overflow: hidden;
}

.doctor-card::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 120px;
  height: 120px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 0 0 0 100%;
}

.avatar-container {
  position: relative;
  margin-right: 25px;
}

.doctor-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.status-indicator {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #e74c3c;
  border: 2px solid white;
}

.status-indicator.online {
  background-color: #2ecc71;
}

.doctor-meta {
  flex: 1;
}

.doctor-meta h2 {
  font-size: 1.8rem;
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.title-badge {
  display: inline-block;
  background-color: #3498db;
  color: white;
  font-size: 0.9rem;
  padding: 3px 10px;
  border-radius: 15px;
  margin-left: 10px;
  vertical-align: middle;
}

.department {
  color: #7f8c8d;
  margin: 0 0 15px 0;
  font-size: 1.1rem;
}

.contact-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.contact-item {
  display: flex;
  align-items: center;
  color: #555;
}

.icon-phone {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #3498db;
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
  margin-right: 5px;
}

.doctor-bio {
  flex: 1;
  padding: 10px 20px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  font-style: italic;
  color: #555;
  max-width: 400px;
}

/* 排班表格样式 */
.schedule-container {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 30px;
}

.week-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.nav-button {
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  padding: 8px 15px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.2s;
}

.nav-button:hover {
  background-color: #e9ecef;
  border-color: #adb5bd;
}

.icon-arrow-left, .icon-arrow-right {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #555;
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 18l-6-6 6-6'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
}

.icon-arrow-right {
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 18l6-6-6-6'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
}

.current-week {
  font-weight: bold;
  color: #2c3e50;
}

.schedule-grid {
  display: grid;
  grid-template-columns: 120px repeat(5, 1fr);
  gap: 1px;
  background-color: #eee;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #eee;
}

.grid-header {
  display: contents;
}

.grid-header > div {
  background-color: #34495e;
  color: white;
  padding: 12px;
  text-align: center;
}

.grid-day {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.weekday {
  font-weight: bold;
  margin-bottom: 5px;
}

.date {
  font-size: 0.9rem;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.date.today {
  background-color: #e74c3c;
  color: white;
}

.grid-row {
  display: contents;
}

.grid-time-label {
  background-color: #f8f9fa;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-weight: bold;
}

.time-range {
  font-size: 0.8rem;
  color: #7f8c8d;
  font-weight: normal;
  margin-top: 3px;
}

.grid-cell {
  background-color: white;
  padding: 10px;
  min-height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.shift-indicator {
  width: 120px;
  padding: 10px;
  border-radius: 8px;
  text-align: center;
  font-size: 0.9rem;
  background-color: #f0f5ff;
  color: #409EFF;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 60px;
  justify-content: center;
  transition: all 0.3s;
}

.shift-indicator.working {
  background-color: #f0f9eb;
  color: #67C23A;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.1);
}

.shift-text {
  margin-bottom: 5px;
  word-break: break-all;
}

.icon-check {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: currentColor;
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 6L9 17l-5-5'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
  margin-top: 5px;
}

/* 统计卡片样式 */
.stats-card {
  display: flex;
  justify-content: space-around;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stat-item {
  text-align: center;
  padding: 0 15px;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  color: #7f8c8d;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .doctor-card {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .avatar-container {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .doctor-bio {
    max-width: 100%;
    margin-top: 15px;
  }
  
  .schedule-grid {
    grid-template-columns: 80px repeat(5, 1fr);
    font-size: 0.9rem;
  }
  
  .grid-time-label {
    padding: 10px 5px;
  }
  
  .shift-indicator {
    width: 60px;
    padding: 5px;
  }
  
  .stats-card {
    flex-direction: column;
    gap: 20px;
  }
}

.icon-location {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: currentColor;
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z'%3E%3C/path%3E%3Ccircle cx='12' cy='10' r='3'%3E%3C/circle%3E%3C/svg%3E") no-repeat center;
}
</style>